package com.example.psysystemhomework.ui.notifications;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.lights.LightState;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.example.psysystemhomework.LoginActivity;
import com.example.psysystemhomework.R;
import com.example.psysystemhomework.alert.EmotionChartAlert;
import com.example.psysystemhomework.alert.HoriAlert;
import com.example.psysystemhomework.alert.MyInformationAlert;
import com.example.psysystemhomework.bean.BackBean;
import com.example.psysystemhomework.bean.CountBeanStatic;
import com.example.psysystemhomework.bean.EmotionBean;
import com.example.psysystemhomework.bean.EmotionTo;
import com.example.psysystemhomework.bean.UserBean;
import com.example.psysystemhomework.databinding.FragmentNotificationsBinding;
import com.example.psysystemhomework.util.AppManager;
import com.example.psysystemhomework.util.ChartUtil;
import com.example.psysystemhomework.util.NetUtil;
import com.example.psysystemhomework.util.ShareUtil;
import com.github.mikephil.charting.charts.PieChart;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class NotificationsFragment extends Fragment {

    private NotificationsViewModel notificationsViewModel;
    private FragmentNotificationsBinding binding;
    private TextView userName;
    private ImageView imageTou;
    private PieChart pieChart;
    private RelativeLayout reaLayout;
    private Timer timer;
    private TextView txShow;
    private ArrayList<EmotionBean> list;
    private TextView replyCount;
    private TextView uploadCount;
    private TextView activeCount;
    private Button btEmotion;
    private Button btFood;
    private ProgressDialog progressDialog;

    private ArrayList<EmotionTo> listAlert = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel =
                new ViewModelProvider(this).get(NotificationsViewModel.class);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        initView();
        initChart();
        initData();
        setClick();

        return root;
    }

    private void initChart() {
        ChartUtil chartUtil = new ChartUtil(pieChart);
        list = new ArrayList<>();
        Random random = new Random();
        list.add(new EmotionBean(random.nextInt(100), "happy"));
        list.add(new EmotionBean(random.nextInt(100), "angry"));
        list.add(new EmotionBean(random.nextInt(100), "sad"));
        chartUtil.showPieChart(list, 10);
        setRoaShow();

    }

    private void setRoaShow() {
        final int[] i = {0};
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                pieChart.setRotation((i[0]) % 360);
                i[0] += 5;
            }
        }, 0, 50);
    }

    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    private void initData() {
        ShareUtil shareUtil = new ShareUtil(getContext());
        UserBean user = shareUtil.getUser();
        if (user != null) {
            userName.setText(user.getName());
            Glide.with(getContext())
                    .load(user.getIconBean().getUrl())
                    .into(imageTou);
        }

        uploadCount.setText(CountBeanStatic.upload_count == 0 ? "null" : CountBeanStatic.upload_count + "");
        replyCount.setText(CountBeanStatic.reply_count == 0 ? "null" : CountBeanStatic.reply_count + "");
        Random random = new Random();
        activeCount.setText(random.nextInt(3000) + "");

    }

    private void setClick() {
        userName.setOnClickListener(view -> {
            ShareUtil shareUtil = new ShareUtil(getContext());
            UserBean user = shareUtil.getUser();
            if (shareUtil.getUser() == null) {
                AppManager appManager = AppManager.getAppManager();
                LoginActivity loginActivity = new LoginActivity();
                appManager.addActivity(loginActivity);
                Intent intent = new Intent(getActivity(), appManager.currentActivity().getClass());
                startActivity(intent);
            } else {
                userName.setText(user.getName());
            }


        });


        imageTou.setOnClickListener(view -> {
            MyInformationAlert myInformationAlert = new MyInformationAlert(getContext());
            myInformationAlert.showAlert();
        });


        txShow.setOnClickListener(view -> {
            Toast.makeText(getContext(), "打开详情", Toast.LENGTH_SHORT).show();
            EmotionChartAlert emotionChartAlert = new EmotionChartAlert(getContext(), list);
            emotionChartAlert.showEmotionChart();
        });

        btEmotion.setOnClickListener(view -> {
            progressDialog.show();
            NetUtil netUtil = new NetUtil(getContext());
            new Thread() {
                @Override
                public void run() {
                    JSONObject circleData = netUtil.getCircleData();
                    Gson gson = new Gson();
                    try {
                        String data = circleData.get("data").toString();
                        listAlert = gson.fromJson(data, new TypeToken<List<EmotionTo>>() {
                        }.getType());
                        EventBus.getDefault().post("emotion");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    super.run();
                }
            }.start();

        });


        btFood.setOnClickListener(view -> {
            String url = "mqqwpa://im/chat?chat_type=wpa&uin=1277299835";
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

        });
    }


    @Override
    public void onResume() {
        initData();
        super.onResume();
    }

    private void initView() {
        EventBus.getDefault().register(this);
        userName = binding.userName;
        txShow = binding.txShow;
        imageTou = binding.imageTou;
        pieChart = binding.pieChart;
        reaLayout = binding.reaLayout;
        replyCount = binding.replyCount;
        uploadCount = binding.uploadCount;
        activeCount = binding.activeCount;
        btEmotion = binding.btEmotion;
        btFood = binding.btFood;
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        binding = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String s) {
        if (s.equals("emotion")) {
            HoriAlert horiAlert = new HoriAlert(getContext(), listAlert);
            horiAlert.showChart();
        }
        progressDialog.cancel();


    }
}